package com.ycy.lock;

import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class Producer1 {

  static volatile int i = 0;

  public static void main(String[] args) {

    int thread = 50;
    CountDownLatch countDownLatch = new CountDownLatch(thread);
    Long l = System.currentTimeMillis();
    for (int j = 0; j < thread; j++) {
      new Thread(new Runnable() {
        @Override
        public void run() {

          try {
            Lock lock = new Lock();
            count(lock);
          } catch (IOException | KeeperException | InterruptedException e) {
            e.printStackTrace();
          }

          countDownLatch.countDown();
        }
      }).start();
    }

    try {
      countDownLatch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    //54034耗时
    //99950 完成 ！！！
    System.out.println((System.currentTimeMillis() - l) + "耗时");
    System.out.println(i + " 完成 ！！！ ");

  }

  public static void count(Lock lock) throws KeeperException, InterruptedException {

    lock.tryLock();
    int b = i;
    Thread.sleep(10);
    b = b + 1;
    i = b;
//      System.out.println(Thread.currentThread().getName());
    lock.release();

  }


}
